<?php

namespace app\model\user;

use app\base\BaseModel;

/**
 * 模型-UserIntegralLogModel
 * Class UserIntegralLogModel
 * @package app\model
 */
class UserIntegralLogModel extends BaseModel
{

    protected $name = 'user_integral_log';

    /**
     * 添加积分日志
     * @param $user_id
     * @param $integral
     * @param $type
     * @param string $detail
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function addIntegralLog($user_id, $integral, $type, $detail = "")
    {
        $user_model = new UserModel();
        $user_model->startTrans();
        $user_data = $user_model->where(['id' => $user_id])->field('integral')->find();
        $now_integral = $user_data['integral'];
        switch ($type) {
            case 'add':
                $now_integral = intval($now_integral) + intval($integral);
                if (empty($detail)) {
                    $detail = "获得积分";
                }
                break;
            case 'sub':
                $now_integral = intval($now_integral) - intval($integral);
                if (empty($detail)) {
                    $detail = "扣除积分";
                }
                break;
            case 'use':
                $now_integral = intval($now_integral) - intval($integral);
                if (empty($detail)) {
                    $detail = "使用积分";
                }
                break;
        }
        $in_integral = [
            'user_id' => $user_id,
            'last_number' => $user_data['integral'],
            'number' => $integral,
            'detail' => $detail,
            'type' => $type,
            'add_time' => time(),
            'add_date' => date("Y-m-d H:i:s"),
        ];
        $ret = self::insert($in_integral);
        if ($ret !== false) {
            $up_data = [
                'integral' => $now_integral
            ];
            $ret = $user_model->where(['id' => $user_id])->update($up_data);
            if ($ret !== false) {
                $user_model->commit();
                return true;
            }
        }
        $user_model->rollback();
        return false;
    }

}
